﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using OnlineVideos.View_Models;
using OnlineVideos.Common;
//using OnlineVideos.Data;
using Common.Library;
using OnlineVideos;
using Microsoft.Phone.BackgroundAudio;
using System.ComponentModel;
using System.Windows.Threading;
using OnlineVideos.Data;
//using OnlineVideos.Game;
using OnlineVideos.UI;
using Microsoft.Phone.Shell;
using OnlineVideos.Utilities;
using Common.Utilities;
using System.Windows.Media.Imaging;
using PicasaMobileInterface;
using OnlineVideos.Entities;
using System.Threading.Tasks;
using System.Windows.Controls.Primitives;

namespace OnlineMovies.Views
{
    public partial class MusicDetail : PhoneApplicationPage
    {
        #region GlobalDeclaration
        bool appbarvisible = true;
        ListPicker pickr = default(ListPicker);
        Popup pop = new Popup();
        string pivotindex = string.Empty;
        string navigationvalue = string.Empty;
        PivotItem currentItem = default(PivotItem);
        string background = "0";
        string id = "";
        string Atitle = "";
        string chapter = string.Empty;
        string type = string.Empty;
        string secondarytileindex = string.Empty;
        public DispatcherTimer storyboardtimer;
        #endregion

        #region Constructor
        public MusicDetail()
        {
            try
            {
            InitializeComponent();
            Loaded += new RoutedEventHandler(MusicDetail_Loaded);
            if (AppSettings.ShowID != "0")
            {
                pvtMainDetails.Background = ShowDetail.LoadShowPivotBackground(AppSettings.ShowUniqueID);
                tblkVideosTitle.Text = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID).Title.ToUpper();
                background = "1";
            }


            if (!ShowCastManager.ShowGamePivot(AppSettings.ShowID))
            {
                pvtMainDetails.Items.Remove(gamepivot);
            }
            }
            catch (Exception ex)
            {

               Exceptions.SaveOrSendExceptions("Exception in MusicDetail Method In MusicDetail.cs file.", ex);
        }

        }
        #endregion

        #region "Common Methods"

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
                FlurryWP8SDK.Api.EndTimedEvent("MusicDetail Page");
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in OnNavigatedFrom Method In MusicDetail.cs file.", ex);
            }
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            try
            {
             
                FlurryWP8SDK.Api.LogPageView();
                int showid = AppSettings.ShowUniqueID;

                if (Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.Status != "Custom")
            {
                this.ApplicationBar.IsVisible = false;
                appbarvisible = false;
            }
            else
            {
                this.ApplicationBar.IsVisible = true;
            }
            if (NavigationContext.QueryString.TryGetValue("navigationvalue", out navigationvalue))
            {

                if (navigationvalue == "1")
                {
                    if (NavigationContext.QueryString.TryGetValue("pivotindex", out pivotindex))

                        pvtMainDetails.SelectedIndex = Convert.ToInt32(pivotindex);
                    Constants.navigationvalue++;
                }
                else
                {
                    if (NavigationContext.QueryString.TryGetValue("pivotindex", out pivotindex))
                        pvtMainDetails.SelectedIndex = Convert.ToInt32(pivotindex);
                    Constants.navigationvalue--;
                }
                while (NavigationService.BackStack.Count() > 1)
                {
                    if (!NavigationService.BackStack.FirstOrDefault().Source.OriginalString.Contains("MusicDetail"))
                    {
                        NavigationService.RemoveBackEntry();
                    }
                    else
                    {
                        NavigationService.RemoveBackEntry();
                        break;
                    }
                }
            }
            performanceProgressBar.IsIndeterminate = true;
            if (NavigationContext.QueryString.TryGetValue("id", out id))
            {
            }
            if (NavigationContext.QueryString.TryGetValue("chapter", out chapter))
            {
                Common.Library.AppState.searchtitle = chapter;
            }
            if (NavigationContext.QueryString.TryGetValue("type", out type))
            {
            }
            if (NavigationContext.QueryString.TryGetValue("secondarytileindex", out secondarytileindex))
            {
                pvtMainDetails.SelectedIndex = Convert.ToInt32(secondarytileindex);
            }
            if (type == "search")
            {
                NavigationService.RemoveBackEntry();
            }
        }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in OnNavigatedTo Method In MusicDetail.cs file.", ex);
            }
        }
        public void addgame()
        {
            try
            {
            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {


                if (ShowCastManager.ShowGamePivot(AppSettings.ShowID))
                {

                    storyboardtimer = new DispatcherTimer();
                    storyboardtimer.Interval = TimeSpan.FromSeconds(2);
                    storyboardtimer.Tick += new EventHandler(storyboardtimer_Tick);
                    storyboardtimer.Start();
                }


            });
            }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in addgame Method In MusicDetail.cs file.", ex);
            }

        }
        #endregion

        #region PageLoad
        void MusicDetail_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                LoadAds();
                FlurryWP8SDK.Api.LogEvent("MusicDetail Page", true);
            int showid = AppSettings.ShowUniqueID;
            string sharedstatus = Task.Run(async () => await Constants.connection.Table<ShowList>().Where(i => i.ShowID == showid).FirstOrDefaultAsync()).Result.ShareStatus;
            if (sharedstatus == "Shared To Blog")
                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = "share this" + " " + AppResources.Type + "(" + "Shared)";
            else
                ((ApplicationBarMenuItem)ApplicationBar.MenuItems[0]).Text = "share this" + " " + AppResources.Type + "(" + "Not Shared)";
            if (background == "0")
            {

                tblkVideosTitle.Text = OnlineShow.GetShowDetail(AppSettings.ShowUniqueID).Title.ToUpper();
            }


            PageHelper.RemoveEntryFromBackStack(AppResources.DetailPageName);
            if (Constants.topsongnavigation != "")
            {
                pvtMainDetails.SelectedIndex = Convert.ToInt32(Constants.topsongnavigation);
                Constants.topsongnavigation = "";
            }
            performanceProgressBar.IsIndeterminate = false;
            }
            catch (Exception ex)
            {

                Exceptions.SaveOrSendExceptions("Exception in MusicDetail_Loaded Method In MusicDetail.cs file.", ex);
            }

        }
        #endregion

        #region Events
        private void LoadAds()
        {
            try
            {
                PageHelper.LoadAdControl(LayoutRoot, adstackpl, 1);
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in LoadAds Method In SongDetails file", ex);
                string excepmess = "Exception in LoadAds Method In SongDetails file.\n\n" + ex.Message + "\n\n StackTrace :- \n" + ex.StackTrace;
            }

        }
        void storyboardtimer_Tick(object sender, EventArgs e)
        {
            try
            {
            if (pvtMainDetails.SelectedIndex == 2)
            {
                if (OnlineVideos.Game.GameInstance.gameopened == false)
                {
                    foreach (OnlineVideos.Game.MemoryCard m in OnlineVideos.Game.GameInstance.stopstoryboard)
                    {
                        m.storyboardfromx = "3";
                        m.storyboardtox = "-3";
                        m.storyboardfromy = "3";
                        m.storyboardtoy = "-3";
                        m.storyboardfromz = "3";
                        m.storyboardtoz = "-3";
                    }
                    storyboardtimer.Stop();

                }


            }
        }
            catch (Exception ex)
            {
                
                  Exceptions.SaveOrSendExceptions("Exception in storyboardtimer_Tick Method In MusicDetail.cs file.", ex);
            }
        }
        private void pvtMainDetails_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
            currentItem = e.AddedItems[0] as PivotItem;
            if (appbarvisible == true)
            {
                if (currentItem != null)
                {
                    if (currentItem.Header.ToString() == "detail")
                    {
                        if (this.ApplicationBar.MenuItems.Count == 2)
                            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Edit" + " " + "description";
                        else
                        {
                            ApplicationBarMenuItem appBarMenuitem = new ApplicationBarMenuItem("Edit" + " " + "description");
                            appBarMenuitem.Click += btnadd_Click_1;
                            this.ApplicationBar.MenuItems.Add(appBarMenuitem);
                        }
                        //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = ".";
                        //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = false;

                    }
                    else if (currentItem.Header.ToString() == "lyrics")
                    {
                        if (this.ApplicationBar.MenuItems.Count == 2)
                            this.ApplicationBar.MenuItems.RemoveAt(1);
                        //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = ".";
                        //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = false;

                    }
                    else if (currentItem.Header.ToString() == "game")
                    {
                        if (this.ApplicationBar.MenuItems.Count == 2)
                            this.ApplicationBar.MenuItems.RemoveAt(1);
                        //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = ".";
                        //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = false;

                    }
                    else
                    {
                        if (this.ApplicationBar.MenuItems.Count < 2)
                        {
                            ApplicationBarMenuItem appBarMenuitem = new ApplicationBarMenuItem("Add" + " " + currentItem.Header.ToString());
                            appBarMenuitem.Click += btnadd_Click_1;
                            this.ApplicationBar.MenuItems.Add(appBarMenuitem);
                        }
                        else
                        {
                            ((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).Text = "Add" + " " + currentItem.Header.ToString();
                        }
                        //((ApplicationBarMenuItem)ApplicationBar.MenuItems[1]).IsEnabled = true;

                    }
                }
            }
            if (pvtMainDetails.SelectedIndex == 2)
            {
                performanceProgressBar.IsIndeterminate = true;
                BackgroundHelper bwhelper = new BackgroundHelper();
                bwhelper.AddBackgroundTask(
                                            (object s, DoWorkEventArgs a) =>
                                            {
                                                addgame();
                                            },
                                             (object s, RunWorkerCompletedEventArgs a) =>
                                             {
                                                 performanceProgressBar.IsIndeterminate = false;
                                             }
                                          );


                bwhelper.RunBackgroundWorkers();

                //bwhelper.AddScheduledBackgroundTask(RegisterShowDownloadAgent, TimeSpan.FromSeconds(10));

                bwhelper.StartScheduledTasks();
            }
            else
            {
                if (BackgroundAudioPlayer.Instance.PlayerState == PlayState.Playing)
                {
                    if (BackgroundAudioPlayer.Instance != null && BackgroundAudioPlayer.Instance.Track.Source.ToString().Contains("Claps.mp3"))
                    {
                        BackgroundAudioPlayer.Instance.Stop();
                    }
                }
                }
            }
            catch (Exception ex)
            {
                
                  Exceptions.SaveOrSendExceptions("Exception in pvtMainDetails_SelectionChanged Method In MusicDetail.cs file.", ex);
            }
        }
        private void imgTitle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            NavigationService.Navigate(NavigationHelper.MainPanoramaPage);
        }
        private void btnshare_Click_1(object sender, EventArgs e)
        {
            try
            {
 if (NetworkHelper.IsNetworkAvailableForDownloads())
            {
            UploadToBlog upload = new UploadToBlog(AppSettings.ShowUniqueID, page1: this);
}
            }
            catch (Exception ex)
            {
                
               Exceptions.SaveOrSendExceptions("Exception in btnshare_Click_1 Method In MusicDetail.cs file.", ex);
            }

        }
        private void btnadd_Click_1(object sender, EventArgs e)
        {

            try
            {
            if ((sender as ApplicationBarMenuItem).Text.Contains("cast"))
            {
                Constants.DownloadTimer.Stop();
                NavigationService.Navigate(new Uri("/Views/AddCast.xaml", UriKind.RelativeOrAbsolute));
            }
            else if ((sender as ApplicationBarMenuItem).Text.Contains("description"))
            {
                Constants.DownloadTimer.Stop();
                Constants.editdescription = true;
                NavigationService.Navigate(new Uri("/Views/Description.xaml", UriKind.RelativeOrAbsolute));
            }
            else
            {

                if ((sender as ApplicationBarMenuItem).Text.Contains("chapters"))
                {
                    Constants.DownloadTimer.Stop();
                    Constants.Linkstype = "Movies";
                    NavigationService.Navigate(new Uri("/Views/LinksFromOnline.xaml?language=" + string.Empty, UriKind.Relative));
                }
                else if ((sender as ApplicationBarMenuItem).Text.Contains("songs"))
                {
                    Constants.DownloadTimer.Stop();
                    Constants.Linkstype = "Songs";
                    NavigationService.Navigate(new Uri("/Views/LinksFromOnline.xaml?language=" + string.Empty, UriKind.Relative));
                }
                else if ((sender as ApplicationBarMenuItem).Text.Contains("audio"))
                {
                    Constants.DownloadTimer.Stop();
                    Constants.Linkstype = "Audio";

                    if (ResourceHelper.ProjectName == "Indian Cinema")
                    {
                        StackPanel messagestk = new StackPanel();
                        messagestk.Background = new SolidColorBrush(Colors.Black);
                        messagestk.Opacity = 0.8;
                        messagestk.Margin = new Thickness(70, 130, 0, 0);
                        messagestk.HorizontalAlignment = HorizontalAlignment.Center;
                        messagestk.VerticalAlignment = VerticalAlignment.Center;
                        messagestk.Orientation = System.Windows.Controls.Orientation.Vertical;
                        messagestk.Height = 300;
                        messagestk.Width = 300;

                        TextBlock tblklinktype = new TextBlock();
                        tblklinktype.Height = 60;
                        tblklinktype.Width = 200;
                        tblklinktype.Foreground = new SolidColorBrush(Colors.White);
                        tblklinktype.Margin = new Thickness(-10, 60, 0, 0);
                        tblklinktype.FontSize = 28;
                        tblklinktype.Text = "Select Language";
                        pickr = new ListPicker();
                        pickr.Width = 170;
                        pickr.Margin = new Thickness(-20, -10, 0, 0);

                        pickr.Items.Add("Hindi");
                        pickr.Items.Add("Telugu");
                        pickr.Items.Add("Tamil");
                        StackPanel imgstck = new StackPanel();
                        imgstck.Orientation = System.Windows.Controls.Orientation.Horizontal;
                        //imgstck.Height = 100;
                        //imgstck.Width = 300;
                        imgstck.Margin = new Thickness(45, 30, 0, 0);
                        Image saveimg = new Image();
                        saveimg.Height = 48;
                        saveimg.Width = 48;
                        saveimg.Source = new BitmapImage(new Uri("Images/rating/appbar.check.rest.png", UriKind.Relative));
                        saveimg.MouseLeftButtonDown += saveimg_MouseLeftButtonDown;
                        Image cancelimg = new Image();
                        cancelimg.Height = 48;
                        cancelimg.Width = 48;
                        cancelimg.Margin = new Thickness(40, 0, 0, 0);
                        cancelimg.Source = new BitmapImage(new Uri("Images/rating/appbar.cancel.rest.png", UriKind.Relative));
                        cancelimg.MouseLeftButtonDown += cancelimg_MouseLeftButtonDown;
                        imgstck.Children.Add(saveimg);
                        imgstck.Children.Add(cancelimg);
                        messagestk.Children.Add(tblklinktype);
                        messagestk.Children.Add(pickr);
                        messagestk.Children.Add(imgstck);

                        pop.Child = messagestk;
                        pop.IsOpen = true;
                        pickr.SelectionChanged += pickr_SelectionChanged;
                    }
                    else
                    {
                        NavigationService.Navigate(new Uri("/Views/LinksFromOnline.xaml?language=Hindi", UriKind.Relative));
                    }
                }

                //NavigationService.Navigate(new Uri("/Views/AddLinks.xaml?linktype=" + type, UriKind.RelativeOrAbsolute));
            }
        }
            catch (Exception ex)
            {
                
                Exceptions.SaveOrSendExceptions("Exception in btnadd_Click_1 Method In MusicDetail.cs file.", ex);
            }
        }
        void cancelimg_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            pop.IsOpen = false;
        }

        void saveimg_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            pop.IsOpen = false;
            NavigationService.Navigate(new Uri("/Views/LinksFromOnline.xaml?language=" + pickr.SelectedItem.ToString(), UriKind.Relative));
        }

        void pickr_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {


            string language = (sender as ListPicker).SelectedItem.ToString();


        }
        #endregion


    }
}